package rabbitmq.A05Topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import rabbitmq.RabbitMQUtil;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * topic 类型的exchange可以像direct以及fanout一样工作
 * 1. bindkey使用#,将会完全匹配所有的routingkey，即不用识别routingkey,工作模式与fanout相同
 * 2. bindkey不使用#和*，将会和direct工作模式相同，单词匹配
 */
public class TopicPublish {
    private static String exchangeDeclare = "logs3";
    private static Random random = new Random();
    private static String[] messageType = {"INFO", "WARNING", "ERR"};

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = RabbitMQUtil.newConnection();
        Channel channel = RabbitMQUtil.newChannel(connection);
        channel.exchangeDeclare(exchangeDeclare, BuiltinExchangeType.TOPIC);
        Integer incr = 1;
        while (true) {
            String msgType = getMessageType();
            String msgFmt = "[%s]:message-[%d]";
            msgType = (incr % 2 == 0 ? "even" : "odd") + "." + msgType;
            channel.basicPublish(exchangeDeclare, msgType, null, String.format(msgFmt, msgType, incr++).getBytes());
            TimeUnit.MILLISECONDS.sleep(5);
        }
    }

    private static String getMessageType() {
        Integer rand = random.nextInt() % 10;
        if (rand.compareTo(5) <= 0) return messageType[0];
        if (rand.compareTo(8) <= 0) return messageType[1];
        return messageType[2];
    }
}
